package com.ruoyi.iot.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.iot.channel.translator.impl.TransformCmdServiceImpl;
import com.ruoyi.iot.domain.IotCmd;
import com.ruoyi.iot.domain.IotCmdExplain;
import com.ruoyi.iot.domain.dto.ExplainTranslateDTO;
import com.ruoyi.iot.domain.vo.drop.CmdExplainInfo;
import com.ruoyi.iot.domain.vo.enums.ESponsor;
import com.ruoyi.iot.domain.vo.plus.IotCmdExplainPlus;
import com.ruoyi.iot.service.IIotCmdExplainService;
import com.ruoyi.iot.service.impl.IotCmdServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.util.HexBin;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;

/**
 * 指令解释Controller
 *
 * @author zxq
 * @date 2022-09-26
 */
@RestController
@Slf4j
@RequestMapping("/explain")
public class IotCmdExplainController extends BaseController
{
    /**
     * 指令解释
     */
    @Autowired
    private IIotCmdExplainService iotCmdExplainService;

    /**
     * 指令服务
     */
    @Autowired
    private IotCmdServiceImpl iotCmdServiceImpl;

    /**
     * cmd翻译服务
     */
    @Autowired
    private TransformCmdServiceImpl transformCmdService;


    /**
     * 查询指令解释列表
     */
    @RequiresPermissions("iot:explain:list")
    @GetMapping("/list")
    public CmdExplainInfo list(IotCmdExplain iotCmdExplain)
    {
        startPage();
        List<IotCmdExplain> list = iotCmdExplainService.selectIotCmdExplainList(iotCmdExplain);
        List<IotCmdExplainPlus> plusList = new ArrayList<>();
        for(IotCmdExplain item : list) {
            IotCmdExplainPlus iotCmdExplainPlus = new IotCmdExplainPlus();
            BeanUtils.copyProperties(item,iotCmdExplainPlus);
            iotCmdExplainPlus.setCmdName(iotCmdServiceImpl.selectIotCmdById(item.getCmdId()).getName());
            String cmdJson = JSON.parseObject(item.getJson()).getString("data");
            log.info("cmdJson:" + cmdJson);
            iotCmdExplainPlus.setCmdJson(cmdJson);
            plusList.add(iotCmdExplainPlus);
        }


        CmdExplainInfo cmdExplainInfo = new CmdExplainInfo();
        cmdExplainInfo.setCode(200);
        cmdExplainInfo.setCmdList(iotCmdServiceImpl.selectIotCmdList(new IotCmd()));
        cmdExplainInfo.setMsg("查询成功");
        cmdExplainInfo.setRows(plusList);
        cmdExplainInfo.setTotal((new PageInfo(list)).getTotal());

        log.info("explain:" + JSON.toJSONString(cmdExplainInfo));

        return cmdExplainInfo;
    }

    /**
     * 导出指令解释列表
     */
    @RequiresPermissions("iot:explain:export")
    @Log(title = "指令解释", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IotCmdExplain iotCmdExplain)
    {
        List<IotCmdExplain> list = iotCmdExplainService.selectIotCmdExplainList(iotCmdExplain);
        ExcelUtil<IotCmdExplain> util = new ExcelUtil<IotCmdExplain>(IotCmdExplain.class);
        util.exportExcel(response, list, "指令解释数据");
    }

    /**
     * 获取指令解释详细信息
     */
    @RequiresPermissions("iot:explain:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(iotCmdExplainService.selectIotCmdExplainById(id));
    }

    /**
     * 新增指令解释
     */
    @RequiresPermissions("iot:explain:add")
    @Log(title = "指令解释", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IotCmdExplain iotCmdExplain)
    {
        return toAjax(iotCmdExplainService.insertIotCmdExplain(iotCmdExplain));
    }

    /**
     * 修改指令解释
     */
    @RequiresPermissions("iot:explain:edit")
    @Log(title = "指令解释", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody IotCmdExplain iotCmdExplain)
    {
        return toAjax(iotCmdExplainService.updateIotCmdExplain(iotCmdExplain));
    }

    /**
     * 删除指令解释
     */
    @RequiresPermissions("iot:explain:remove")
    @Log(title = "指令解释", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(iotCmdExplainService.deleteIotCmdExplainByIds(ids));
    }

    /**
     * 指令翻译
     * @param explainTranslateDTO 指令翻译
     * @return 返回值
     */
    @PostMapping("/translate")
    public ExplainTranslateDTO translate(@RequestBody ExplainTranslateDTO explainTranslateDTO) {
           ESponsor eSponsor =  ESponsor.getType(explainTranslateDTO.getSponsor().intValue());
           Long cmdId =  explainTranslateDTO.getCmdId();
           String cmdData =  explainTranslateDTO.getData();
           log.info("json:" + JSON.toJSONString(explainTranslateDTO));
           switch (eSponsor) {
               case device:
                   JSONObject json = transformCmdService.deviceTransform(cmdId, HexBin.stringToBytes(cmdData));
                   explainTranslateDTO.setData(json.toJSONString());
                   break;
               case platform:
                   byte[] hexBuff = transformCmdService.platformTransform(cmdId, JSON.parseObject(cmdData));
                   if(hexBuff == null) {
                       explainTranslateDTO.setData("转换失败，请重新配置指令！");
                   } else {
                       explainTranslateDTO.setData(HexBin.bytesToString(hexBuff));
                   }
                   break;
           }
           log.info("result:" + JSON.toJSONString(explainTranslateDTO));

           return explainTranslateDTO;
    }




}
